package com.github.defense.starter.gateway.launch;

import com.github.defense.common.config.DefenseConfig;
import com.github.defense.common.data.AppInfo;
import com.github.defense.common.enums.SceneEnum;
import com.github.defense.common.utils.NetUtils;
import com.github.defense.starter.common.event.DefenseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * @Author: lettger
 * @Date: 2021/12/4 上午11:32
 */
@Slf4j
public class DefenseRegisterProcessor implements InitializingBean {

    private ApplicationEventPublisher applicationEventPublisher;

    private AppInfo appInfo = new AppInfo();

    public DefenseRegisterProcessor(final DefenseConfig config, final Environment environment, final ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
        String appName = environment.getProperty("spring.application.name");
        String port = environment.getProperty("server.port");
        if (Objects.isNull(config.getAdminAddr()) || Objects.isNull(appName) ) {
            throw new RuntimeException("*** defense gateway config lack ***");
        }
        appInfo.setName(appName);
        appInfo.setPort(port);
        appInfo.setGroup(config.getGroup());
        appInfo.setGateway(true);
        appInfo.setHost(NetUtils.getAddress());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO 后期可以扩展其他的
        log.debug("This is Gateway application info :{}", appInfo);
        applicationEventPublisher.publishEvent(new DefenseEvent("", appInfo, SceneEnum.GATEWAY));
    }
}
